from pydantic import BaseModel
from datetime import datetime
from utils.HashUtils import HashUtils
from ConfigManager import ConfigManager
from llm.SiliconFlowEmbeddingClient import SiliconFlowEmbeddingClient
from typing import Optional, List
from Logger import Logger

# 配置日志
logger = Logger.get_logger(__name__)

class SearchDocument(BaseModel):
    id: str  # 使用文件路径哈希作为唯一ID
    file_path: str  # 文本型的文件路径
    page_number: str  # 页
    file_format: str  # 文件格式，例如 md/txt
    last_modified: datetime  # 最后修改时间
    file_size: int  # 整数型的文件大小
    text_content: str  # 用于Elasticsearch的文本内容
    doc_embedding: list[float]  # 存储文档嵌入的向量，假设为浮点数组

    @classmethod
    def create(cls, file_path: str, page_number: str, text_content: str, file_format: str, size: int):
        def get_embedding(text_content: str) -> Optional[List[float]]:
            """
            获取文档文本内容的嵌入向量

            Returns:
                Optional[List[float]]: 嵌入向量，如果发生错误则返回None
            """
            try:
                # 从配置文件获取token
                config = ConfigManager()
                token = config.get('embedding_key')
                if not token:
                    logger.error("未找到embedding_key配置")
                    return None

                # 将文本内容转换为字符串
                text = str(text_content)
                if not text:
                    logger.error("文档内容为空")
                    return None
                
                # 初始化embedding客户端
                client = SiliconFlowEmbeddingClient(token=token)
                # 获取embedding
                response = client.get_embeddings(text)
                return response
            except Exception as e:
                # 记录错误并返回None
                logger.error(f"获取embedding时发生错误: {str(e)}")
                return None
        if not text_content:
            return None   
        embedding_text_content = get_embedding(text_content)
        if not embedding_text_content:
            return None
        return cls(
            id=HashUtils.get_content_hash(text_content),
            file_path=file_path,
            page_number=page_number,
            file_format=file_format,
            last_modified=datetime.now(),
            file_size=size,
            text_content=text_content,  # 直接使用原始内容作为text_content
            doc_embedding=embedding_text_content  # 嵌入向量
        )
    
